//  实验制作的注释
<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-form layout="inline">
          <a-row :gutter="48">

            <a-col :md="8" :sm="24">
              <a-form-item label="关键字">
                <a-input v-model="queryParam.keywords" placeholder="名称"/>
              </a-form-item>
            </a-col>

            <a-col :md="5" :sm="24">
              <a-form-item
                  label="学段"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
              >
                <a-select
                    optionFilterProp="title"
                    mode="default"
                    v-model="queryParam.learning_section_id"
                    placeholder="选择学段"
                >
                  <a-select-option :key="option.id" v-for="option in learningSection" :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="5" :sm="24">
              <a-form-item
                  label="年级"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
              >
                <a-select
                    optionFilterProp="title"
                    v-model="queryParam.grade_id"
                    placeholder="选择年级"
                >

                  <a-select-option :key="option.id" v-for="option in gradeOptions"   :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="5" :sm="24">
              <a-form-item
                  label="学科"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
              >
                <a-select
                    optionFilterProp="title"
                    mode="default"
                    v-model="queryParam.subject_id"
                    placeholder="选择学科"
                >
                  <a-select-option :key="option.id" v-for="option in subjectOptions" :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>


            <a-col :md="!advanced && 6 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="onSearch">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>

            </span>
            </a-col>

          </a-row>
        </a-form>
      </a-form>

    </div>

    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd" >新建</a-button>
    </div>


    <template>
      <s-table
          ref="table"
          size="default"
          :columns="columns"
          :data="loadData"
          :alert="{ show: true, clear: () => { this.selectedRowKeys = [] } }"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      >

        <span slot="status" slot-scope="status,record">
        <a-badge status="success" v-if="status==1" text="显示" />
        <a-badge status="default" v-else text="隐藏" />
      </span>
        <span slot="action" slot-scope="text, record">
        <template >
          <a @click="handleEdit(record)" v-if="$auth('user.edit')">编辑</a>
          <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗" @confirm="onDelete(record)"  okText="确定" cancelText="取消">
    <a href="javascript:;">删除</a>
            </a-popconfirm>
        </template>

      </span>
      </s-table>
    </template>

    <a-modal
        title="操作"
        :width="800"
        v-model="visible"
        @ok="handleOk"
    >
      <a-spin :spinning="saveLoading">
        <a-form :form="form">
          <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="实验名称"
              hasFeedback
          >
            <a-input v-decorator="[
          'name',
          {rules: [{ required: false, message: '请输入班级名称' }]}
        ]"
                     placeholder="请输入实验名称"/>
          </a-form-item>

          <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="实验说明"
              hasFeedback
          >
            <a-input v-decorator="[
          'explain',
          {rules: [{ required: true, message: '请输入实验说明' }]}
        ]"
                     placeholder="请输入实验说明"/>
          </a-form-item>

          <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="实验要求"
              hasFeedback
          >
            <a-input v-decorator="[
          'demand',
          {rules: [{ required: true, message: '请输入实验要求' }]}
        ]"
                     placeholder="请输入实验要求"/>
          </a-form-item>

          <a-form-item
              label="器材"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
          >
            <a-select
                optionFilterProp="title"
                mode="multiple"
                v-model="formData.material_ids"
                placeholder="选择器材"
            >
              <a-select-option :key="option.id" v-for="option in materialOptions" :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
              label="学段"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
          >
            <a-select
                @change="learningSectionChange"
                optionFilterProp="title"
                mode="default"
                v-model="formData.learning_section_id"
                placeholder="选择学段"
            >
              <a-select-option :key="option.id" v-for="option in learningSection" :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
              label="年级"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
          >
            <a-select
                optionFilterProp="title"
                v-model="formData.grade_id"
                placeholder="选择年级"
            >

              <a-select-option :key="option.id" v-for="option in gradeTreeOptions"   :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
            </a-select>
          </a-form-item>


          <a-form-item
              v-show="!formData.id"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="版本"
              hasFeedback
          >
            <a-select @change="versionChange" v-model="formData.version_id" placeholder="请选择"
                      allowClear >
              <a-select-option v-for="(version,index) in subjectTree" :value="version.id" :key="index">{{version.name}}</a-select-option>
            </a-select>

          </a-form-item>
          <a-form-item
              v-show="!formData.id"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="学科"
              hasFeedback
          >
            <a-select @change="subjectChange"  v-model="formData.subject_id" placeholder="请选择"
                      allowClear >
              <a-select-option v-for="(subject,index) in subjectOptions" :value="subject.id" :key="index">{{subject.name}}</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
              label="所属知识点"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
          >
            <a-tree-select
                v-decorator="[
                  'cate_ids',
                  {rules: [{ required: true, message: '请输入所属知识点' }]}
                ]"
                style=" width: 90% ; margin-right: 10px; "
                :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                :treeData="cateOptions"
                multiple
                allowClear
                treeNodeFilterProp="title"
                placeholder='请选择所属知识点'
                treeDefaultExpandAll
                v-model="formData.cate_ids"
            >
            </a-tree-select>
            <a-popover content="请选择所属知识点,支持多选">
              <a-icon type="question-circle" />
            </a-popover>
          </a-form-item>

<!--          <a-form-item-->
<!--              label="学科"-->
<!--              :labelCol="labelCol"-->
<!--              :wrapperCol="wrapperCol"-->
<!--          >-->
<!--            <a-select-->
<!--                optionFilterProp="title"-->
<!--                mode="default"-->
<!--                v-model="formData.subject_id"-->
<!--                placeholder="选择学科"-->
<!--            >-->
<!--              <a-select-option :key="option.id" v-for="option in subjectOptions" :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>-->
<!--            </a-select>-->
<!--          </a-form-item>-->

          <a-form-item
              label="资源"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
          >
            <a-select
                optionFilterProp="title"
                mode="multiple"
                v-model="formData.resource_ids"
                placeholder="选择资源"
            >
              <a-select-option :key="option.id" v-for="option in resourceOptions" :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
              label="内容详情"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
          >
            <UEditor  style="width: 400px; height:520px;" :ueditorContent.sync="formData.content" ></UEditor>
          </a-form-item>

          <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="审核状态"
              hasFeedback
          >
            <a-radio-group :disabled="formData.id>0" v-model="formData.status" buttonStyle="solid">
              <a-radio-button :value="1">待审核</a-radio-button>
              <a-radio-button :value="2">已审核</a-radio-button>
              <a-radio-button :value="3">审核失败</a-radio-button>
            </a-radio-group>
          </a-form-item>

<!--          <a-form-item-->
<!--              :labelCol="labelCol"-->
<!--              :wrapperCol="wrapperCol"-->
<!--              label="状态"-->
<!--              hasFeedback-->
<!--          >-->
<!--            <r-switch  :formData="formData" field="status" :checkedValue="1" :unCheckedValue="2"  checkedChildren="显示" unCheckedChildren="隐藏" />-->
<!--          </a-form-item>-->

        </a-form>
      </a-spin>
      <template slot="footer">
        <a-button key="cancel" @click="handleCancel">取消</a-button>
        <a-button key="forward" :loading="saveLoading" type="primary" @click="handleOk">保存</a-button>
      </template>
    </a-modal>

  </a-card>
</template>

<script>
import moment from 'moment'
import EditableCell from '@/components/EditableCell/'
import STable from '@/components/table/'
import { experimentAdd,experimentDelete,experimentEdit,experimentDetail,getMakeExperimentList,gradeOptions,
  materialOptions,subjectOptions,learningSection,resourceOptions} from '@/api/s_experiment'
import PicUploader from '@/components/PicUploader/'
import RSwitch from '@/components/RSwitch/'
import {getUserList} from "@/api/user";
import {cateTreeList, studentOptions} from "@/api/exame";
import FileUploader from "@/components/FileUploader/FileUploader/FileUploader";
import UEditor from '@/components/UEditor/'
import {gradeTreeOptions} from "@/api/resource";
import {getSubjectTree} from "@/api/subject";

export default {
  name: 'SubjectList',
  components: {
    PicUploader,EditableCell,RSwitch,STable,UEditor
  },
  data () {
    return {
      saveLoading:false,
      visible: false,
//        description: '全校班级管理。',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
      form: this.$form.createForm(this),
      mdl: {},

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
        pageNo:1,
      },
      // 表头
      columns: [
        {
          title: '名称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' },
        },
        {
          title: '说明',
          dataIndex: 'explain',
        },
        // {
        //   title: '内容',
        //   dataIndex: 'content',
        //   scopedSlots: { customRender: 'content' },
        // },
        {
          title: '年级',
          dataIndex: 'grade_name',
          scopedSlots: { customRender: 'grade_name' },
        },
        {
          title: '学科',
          dataIndex: 'subject_name',
          scopedSlots: { customRender: 'subject_name' },
        },
        {
          title: '学段',
          dataIndex: 'learning_section_name',
          scopedSlots: { customRender: 'learning_section_name' },
        },

        {
          table: '要求',
          dataIndex: 'demand',
          width: '250px',
          scopedSlots: { customRender: 'action' },
        }
      ],

      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        console.log('loadData');
        console.log(this.queryParam);
        this.queryParam = Object.assign(this.queryParam,parameter);
        return getMakeExperimentList(this.queryParam)
            .then(res => {
              console.log('res');
              return res.data
            })
      },
      materialOptions:[],
      list:[],
      cateOptions:[],
      subjectOptions:[],
      resourceOptions:[],
      learningSection:[],
      yearOptions:[],
      gradeOptions:[],
      gradeTreeOptions:[],
      subjectTree:[],
      formData:{
        name:'',
        version_id:undefined,
        id:0,
        rank:0,
        status:1,
        content:'',
      },
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  created () {
  },
  computed:{
  },

  mounted(){
    let that = this;
    // that.getGradeOptions();
    that.getMaterialOptions();
    // that.getSubjectOptions();
    that.getLearningSection();
    that.getResourceOptions();
    that.getSubjectTreeOptions();
  },

  methods: {

    subjectChange(){
      this.formData.cate_ids = [];
      this.getCateOptions();
    },
    getCateOptions(){
      let that = this;
      cateTreeList({
        subject_id: that.formData.subject_id
      })
          .then(res => {
            that.cateOptions =  res.data;
          })
    },
    versionChange(version_id){
      let that = this;
      console.log('versionChange',version_id);
      let currentVersion = that.subjectTree.filter(item =>{
        return item.id == version_id
      });
      console.log('currentVersion',currentVersion);
      that.subjectOptions =  currentVersion[0].children;
      that.formData.subject_id = undefined;
    },
    getSubjectTreeOptions(){
      let that = this;
      getSubjectTree().then(res => {
        that.subjectTree =  res.data
      })
    },
    learningSectionChange(){
      // this.formData.learning_section_id = 0;
      this.getGradeTreeOptions();
    },
    getGradeTreeOptions(){
      let that = this;
      gradeTreeOptions({
        learning_section_id: that.formData.learning_section_id
      })
          .then(res => {
            that.gradeTreeOptions =  res.data;
          })
    },
    getResourceOptions(){
      let that = this;
      resourceOptions()
          .then(res => {
            console.log(res)
            that.resourceOptions =  res.data
          })
    },
    getSubjectOptions(){
      let that = this;
      subjectOptions()
          .then(res => {
            console.log(res)
            that.subjectOptions =  res.data
          })
    },
    getLearningSection(){
      let that = this;
      learningSection()
          .then(res => {
            console.log(res)
            that.learningSection =  res.data
          })
    },
    getGradeOptions(){
      let that = this;
      // console.log('getGradeOptions1')
      gradeOptions()
          .then(res => {
            console.log(res)
            console.log('getGradeOptions2')
            that.gradeOptions =  res.data
          })
    },
    getMaterialOptions(){
      let that = this;
      materialOptions()
          .then(res => {
            res.data.map(item =>{
              item.id =  item.id+'';
            })
            that.materialOptions =  res.data;
          })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleCancel(){
      this.visible = false
    },
    // 增
    handleAdd(record) {
      let that = this;
      that.visible = true;
      that.form.resetFields();
      that.formData = {
        name:'',
        version_id:undefined,
        id:0,
        rank:0,
        status:1,
        content:'',
        cate_ids:[],
        student_ids:[],
        class_ids:[],
      }
      setTimeout( () =>{
        that.form.setFieldsValue({ ...that.formData });
      });
    },
    // 改
    handleEdit(record) {
      let self = this
      this.visible = true
//      this.form.resetFields();
      self.form.setFieldsValue({
        name:'',
      });
      this.formData.id = record.id;
      experimentDetail({ id: record.id }).then(res => {
        setTimeout(()=>{
          self.form.setFieldsValue({...res.data});
        },1)
        self.formData = {...res.data};
      })
      // console.log(this.mdl)
    },
    // 增改 处理
    handleOk(e) {
      let self = this
      e.preventDefault()
      this.form.validateFields((err, values) => {
        console.log('Received values of form: ', err);
        if (!err) {
          // if(!self.formData.year){
          //   self.$message.error('请选择学年');
          //   return ;
          // }
          console.log('Received values of form1111: ', values)
          console.log('Received valuess of formData2222: ', self.formData)
          self.saveLoading = true;
          if(self.formData.id) {
            experimentEdit({
              id:self.formData.id,
              status:self.formData.status,
              // grade_id:self.formData.year,
              explain:values.explain,
              demand:values.demand,
              content:self.formData.content,
              name:values.name,
              material_ids:self.formData.material_ids,
              learning_section_id:self.formData.learning_section_id,
              grade_id:self.formData.grade_id,
              subject_id:self.formData.subject_id,
              resource_ids:self.formData.resource_ids,
              version_id:self.formData.version_id,
              cate_ids:self.formData.cate_ids,

            }).then(res => {
              self.$message.success('修改成功')
              self.$refs.table.refresh(true)
              self.visible = false;
              self.saveLoading = false;
            }).catch(err =>{
              self.$message.error(err.data.msg);
              self.saveLoading = false;
            })
          }else{
            experimentAdd({
              explain:values.explain,
              demand:values.demand,
              content:self.formData.content,
              name:values.name,
              material_ids:self.formData.material_ids,
              learning_section_id:self.formData.learning_section_id,
              grade_id:self.formData.grade_id,
              subject_id:self.formData.subject_id,
              resource_ids:self.formData.resource_ids,
              status:self.formData.status,
              version_id:self.formData.version_id,
              cate_ids:self.formData.cate_ids,

            }).then(res => {
              self.$message.success('新增成功')
              self.$refs.table.refresh(true)
              self.visible = false
              self.saveLoading = false;
            }).catch(err =>{
              self.$message.error(err.data.msg);
              self.saveLoading = false;
            })
          }
        }
      })
    },

    // 查
    onSearch() {
      let self = this;
      self.$refs.table.refresh(true)
    },

    // 删
    onDelete(record) {
      let self = this
      experimentDelete({ id: record.id  }).then(res => {
        self.$message.success('删除成功')
        self.$refs.table.refresh(true)
      }).catch(err =>{
        self.$message.error(err.data.msg)
      })
    },
  },
  watch: {
    /*
     'selectedRows': function (selectedRows) {
     this.needTotalList = this.needTotalList.map(item => {
     return {
     ...item,
     total: selectedRows.reduce( (sum, val) => {
     return sum + val[item.dataIndex]
     }, 0)
     }
     })
     }
     */
  }
}
</script>